#include "zstring.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

// split a string by spl.
// it will return a strarr if correct
// 	or return NULL if incorrect
char ** zstrtok(const char * const src
	, const char spl
	, int * arrlen
	, int rmemp)
{
	// vars
	char ** vret = NULL; 
	int i = 0;
	int srclen = 0;
	// the preview spliter's index
	int prespi = 0;
	int wordlen = 0;

	// excp
	if (src == NULL
		|| arrlen == NULL)
	{
		vret = NULL;
		goto End;
	}

	//0. get the srclen
	srclen = strlen(src);
	vret = NULL;//(char **)calloc(0, sizeof(char *));
	*arrlen = 0;
	prespi = -1;

	//1. tranverse the first letter to the end letter
	for (i = 0; i < srclen + 1; i++)
	{
		if (spl == src[i] || src[i] == '\0')
		{
			// remove empty
			if (i == 0
				|| src[i - 1] == spl)
			{
				prespi = i;
				continue;
			}

			// the current letter is equal to spl.
			//1. realloc the arr's mem
			vret = (char **)realloc(vret, sizeof(char *) * (1 + *arrlen));
			if (vret == NULL)
			{
				*arrlen = 0;
				goto End;
			}

			//2. calloc the str's mem
			// *arrlen is cur len. [curlen] is the cur item
			//wordlen = (i - (prespi + 1) + 1;
			wordlen = i - prespi;
			// wordlen had included 0
			vret[*arrlen] = (char *)calloc(wordlen, sizeof(char)); 

			// if vret[] == NULL
			if (vret[*arrlen] == NULL)
			{
				// release all mem, and set?
				// break the loop
				break;
			}

			// copy the str
			strncpy(vret[*arrlen], src + (prespi + 1), wordlen - 1);
			
			// set the arrlen;
			(*arrlen)++;
			
			// set prespi
			prespi = i;
		}
	}

	// End
End:
	return vret;
}

// remove vector and set arr NULL
int zstrrmv(char *** parr, const int arrlen)
{
	// variables
	int vret = -1;
	char ** arr = NULL;
	int i = 0;
	
	// exception
	if (NULL == parr)
	{
		vret = -1;
		goto End;
	}
	
	// process
	arr = *parr;
	
	// exception
	if (NULL == arr)
	{
		vret = -1;
		goto End;
	}
	
	// process with arr is not NULL
	for (i = 0; i < arrlen; i++)
	{
		if (arr[i])
		{
			free(arr[i]);
			arr[i] = NULL;
		}
	}
	free(arr);
	*parr = NULL;
	vret = 0;

	// End
End:
	return vret;
}

// trim
int zstrtrim(char * const dest, const char * const src)
{
	int idx = 0;
	int destidx = 0;
	if (!dest || !src)
	{
		return -1;
	}
	for (idx = 0; idx <= strlen(src); idx++)
	{
		//--abc-- // 0123456(7)
		if (isspace(src[idx]))
		{
			continue;
		}
		dest[destidx++] = src[idx];
	}
	return 0;
	
}

int zstrtrim2(char * const dest, const char * const src)
{
	char * tsrc = (char *)src;
	int i = 0;
	int j = 0;

	if (!dest || !src)
	{
		return -1;
	}
	
	while (tsrc[i] != '\0' && isspace(tsrc[i]))
	{
		i++;
	}

	if ('\0' == tsrc[i])
	{
		strcpy(dest, "");
		return 0;
	}

	j = strlen(src) - 1; // \0
	while (j >= i && (isspace(src[j]) || '\0' == src[j]))
	{
		j--;
	}
	
	// strcpy
	strncpy(dest, src + i, j - i + 1); 	
	return 0;
}


